package br.sales.persistence;

import br.sales.entity.ConfigurationValues;
import br.sales.persistence.exception.DBContainerNotInitializedException;

import com.db4o.Db4oEmbedded;
import com.db4o.EmbeddedObjectContainer;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;

public class DB4OAppSingleton {
	
	private static EmbeddedObjectContainer mainContainer;
	
	private EmbeddedConfiguration embeddedConfiguration;
	
	private static DB4OAppSingleton singleton;
	
	public static String DBNAME = ConfigurationValues.databaseDirectoty;
	
	public DB4OAppSingleton(String dbname) {
		if (embeddedConfiguration == null){
			synchronized (IPersistence.class) {
				if (embeddedConfiguration == null){
					embeddedConfiguration = Db4oEmbedded.newConfiguration();
				}
			}
		}
		if (mainContainer == null){
			synchronized (IPersistence.class) {
				if (mainContainer == null){
					mainContainer = Db4oEmbedded.openFile(embeddedConfiguration, DBNAME);
				}
			}
		}

	}	
	
	public static EmbeddedObjectContainer getMainContainer(){
		return mainContainer;
	}
	
	public static ObjectContainer getSession() {
		if (mainContainer != null){
			return mainContainer.ext().openSession();
		} else {
			 getInstance();
			 return getSession();
		}
	}
	
	public static DB4OAppSingleton getInstance(){
		if (singleton == null){
			synchronized (DB4OAppSingleton.class) {
				if (singleton == null){
					singleton = new DB4OAppSingleton(DBNAME);
				}
			}
		}
		return singleton;
	}

	public static void close() throws DBContainerNotInitializedException{
		if (mainContainer != null){
			mainContainer.close();
		}else {
			throw new DBContainerNotInitializedException();
		}
	}
}
